import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { title: '首页' },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { 
          title: '仪表盘',
          icon: 'mdi:view-dashboard',
          requiresAuth: true 
        }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    meta: { 
      title: '系统管理',
      icon: 'mdi:cog',
      requiresAuth: true 
    },
    children: [
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/system/Users.vue'),
        meta: { 
          title: '用户管理',
          icon: 'mdi:account-multiple',
          requiresAuth: true 
        }
      },
      {
        path: 'roles',
        name: 'Roles',
        component: () => import('@/views/system/Roles.vue'),
        meta: { 
          title: '角色管理',
          icon: 'mdi:account-key',
          requiresAuth: true 
        }
      },
      {
        path: 'permissions',
        name: 'Permissions',
        component: () => import('@/views/system/Permissions.vue'),
        meta: { 
          title: '权限管理',
          icon: 'mdi:shield-account',
          requiresAuth: true 
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next('/')
  } else {
    next()
  }
})

export default router